/******************************************************************************
* File:             oled.c
*
* Author:           iysheng@163.com  
* Created:          11/17/22 
* Description:      OLED dispaly thread
*****************************************************************************/

#include <zephyr/zephyr.h>
#include <drivers/spi.h>
#include <string.h>

#define BUF_SIZE        12
uint8_t master_buffer_tx[BUF_SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
uint8_t master_buffer_rx[BUF_SIZE] = {};

const struct device *spi_master = NULL;

/*获取spi1设备实例*/
void spi_master_init(void)
{
    spi_master = DEVICE_DT_GET(DT_NODELABEL(spi1));
    if (spi_master == NULL)
    {
        printk("spi_master: Device is not found.\n");
        return;
    }

    if (!device_is_ready(spi_master))
    {
        printk("spi_master: Device is not ready.\n");
        return;
    }
}

static const struct spi_config spi_cfg = {
    /* 设置SPI配置：8bit数据位, LSB 数据格式，master模式，时钟频率10Mhz */
    .operation = SPI_WORD_SET(8) | SPI_OP_MODE_MASTER | SPI_MODE_CPOL | SPI_MODE_CPHA | SPI_TRANSFER_MSB,
    .frequency = 10000000UL,
};

static struct spi_buf tx_bufs[] = {
    {
        .buf = master_buffer_tx,
        .len = BUF_SIZE,
    },
};
static struct spi_buf_set tx = {
    .buffers = tx_bufs,
    .count = ARRAY_SIZE(tx_bufs)};

int oled_spi_write_data(unsigned char *data, int data_len)
{
    tx_bufs[0].buf = data;
    tx_bufs[0].len = data_len;
    return spi_transceive(spi_master, &spi_cfg, &tx, NULL);
}

extern void ssd1309_init();
extern void oled_draw_point(uint8_t r, uint8_t c, uint8_t t);
void gfx_draw_pixel(int x, int y, unsigned int rgb)
{
	oled_draw_point(x, y, !!(rgb));
}

//UI entry
struct DISPLAY_DRIVER
{
    void (*draw_pixel)(int x, int y, unsigned int rgb);
    void (*fill_rect)(int x0, int y0, int x1, int y1, unsigned int rgb);
} my_driver = {
    .draw_pixel = gfx_draw_pixel,
};

extern void startHelloStar(void* phy_fb, int width, int height, int color_bytes, struct DISPLAY_DRIVER* driver);

void gui_mdelay(unsigned int ms)
{
    k_msleep(ms);
}

/* master线程处理 */
void spi_master_thread(void *v1, void *v2, void *v3)
{
    printk("SPI test start \n");
    spi_master_init();
    ssd1309_init();

    startHelloStar(NULL, 128, 64, 2, &my_driver);
    while (1)
    {
        /*每间隔1S触发一次数据发送和接收*/
        k_msleep(1000);
    }
}
